import React, { useState } from 'react';
import _ from 'lodash';
import { connect } from 'umi';
import { Upload, message, Image } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { getSignOptions } from '@/utils/requestConfig/requestInterceptors';
import styles from './avatarUpload.less';

const maxSize = 2;
const accept = ['image/jpeg', 'image/png', 'image/jpg'];

export default connect(({ user }) => ({
  token: user.token,
}))(({ token, value, onChange }) => {
  const [headers, setHeaders] = useState(getSignOptions());
  const [previewUrl, setPreviewUrl] = useState('');

  return (
    <div className={styles.avatarUploadContent}>
      <Upload
        maxCount={1}
        fileList={value || []}
        listType="picture-card"
        accept={accept.join(',')}
        action={'/api/system/file/upload'}
        headers={_.assign({ saToken: token }, headers)}
        beforeUpload={({ type, size }) => {
          setHeaders(getSignOptions());
          if (!_.includes(accept, type)) {
            message.error(`请上传${accept.join('、').replace('image/', '')}格式的图片!`);
            return false;
          }
          if (size > maxSize * 1024 * 1024) {
            message.error(`图片大小不得超过${maxSize}MB!`);
            return false;
          }
          return true;
        }}
        onPreview={({ url, thumbUrl }) => {
          setPreviewUrl(url || thumbUrl || '');
        }}
        onChange={({ fileList }) => {
          const [fileItem] = fileList;
          if (fileItem && fileItem.status) {
            let errorMsg = '图片上传失败';
            if (fileItem.status === 'done') {
              if (fileItem.response) {
                if (fileItem.response.code === 1) {
                  return onChange([
                    _.assign({}, fileItem, { fileId: fileItem.response.data?.id || null }),
                  ]);
                }
                if (fileItem.response.msg) {
                  errorMsg = fileItem.response.msg;
                }
              }
            }
            if (fileItem.status === 'uploading') {
              return onChange([fileItem]);
            }
            message.error(errorMsg);
            return onChange([]);
          }
          onChange([]);
        }}
      >
        {_.isEmpty(value) && (
          <div>
            <PlusOutlined />
            <div>上传</div>
          </div>
        )}
      </Upload>
      <Image
        preview={{
          visible: !!previewUrl,
          src: previewUrl,
          onVisibleChange: () => {
            setPreviewUrl('');
          },
        }}
      />
    </div>
  );
});
